//
//  UIColor+Extension.swift
//  8btc
//
//  Created by Steven Xie on 2018/8/14.
//  Copyright © 2018年 Hangzhou Shichuo Information Technology Co, Ltd. All rights reserved.
//

import UIKit

// MARK: - UIColor 常用

public extension UIColor {
    static func hex(_ string: String, alpha: CGFloat = 1.0) -> UIColor {
        var cStr: String = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

        if cStr.isEmpty {
            return UIColor.clear
        }

        if cStr.hasPrefix("#") {
            cStr.remove(at: cStr.startIndex)
        }

        let scanner = Scanner(string: cStr)
        scanner.scanLocation = 0
        var rgbValue: UInt64 = 0
        scanner.scanHexInt64(&rgbValue)

        if cStr.count == 8 {
            let a = (rgbValue & 0xFF00_0000) >> 24
            let r = (rgbValue & 0x00FF_0000) >> 16
            let g = (rgbValue & 0x0000_FF00) >> 8
            let b = (rgbValue & 0x0000_00FF)

            return UIColor(
                red: CGFloat(r) / 0xFF,
                green: CGFloat(g) / 0xFF,
                blue: CGFloat(b) / 0xFF,
                alpha: CGFloat(a) / 0xFF
            )
        } else if cStr.count == 6 {
            let r = (rgbValue & 0xFF0000) >> 16
            let g = (rgbValue & 0x00FF00) >> 8
            let b = (rgbValue & 0x0000FF)
            return UIColor(
                red: CGFloat(r) / 0xFF,
                green: CGFloat(g) / 0xFF,
                blue: CGFloat(b) / 0xFF,
                alpha: alpha
            )
        }

        return UIColor.clear
    }

    static func createImage(color: UIColor, size: CGSize) -> UIImage {
        UIImage.imageFromColor(color, width: size.width, height: size.height)
    }

    static var the666666: UIColor {
        return UIColor.hex("666666")
    }
}
